import {
	myRequest
} from '@/static/wx/js/api.js';

// uni.login()封装
const wxLogin = function(openid) {
	return new Promise((resolve, reject) => {
		uni.login({
			success(res) {
				if (res.code) {
					resolve(res.code)
				} else {
					reject(res.errMsg);
				}
			}

		})
	})
}
/*微信小程序登录*/
const wechatAppLogin = function() {
	/*登录提示*/
	loading("正在授权")
	uni.getUserProfile({
		desc: '获取用户授权',
		success: res => {
			let userInfo = res.userInfo;
			wxLogin().then(code => { // 引用uni.login()封装

				myRequest('getOpenid', 'POST', {
						code: code
					}) //获取openid
					.then(function(v) {
						uni.hideLoading();
						uni.setStorageSync("useInfo", res.userInfo);
						uni.setStorageSync("openid", v.openid);
						wx.navigateTo({
							url: '/pages/login/index'
						})
					}, function(error) {
						reject(error);
					})

			})
		}
	})
}

// 获取手机号授权
const getPhoneNumber = function(event) {
	let that = this;
	let code = event.detail.code; //获取手机code
	var promise = new Promise(function(resolve, reject) {
		uni.checkSession({
			success: (res) => {
				myRequest('getPhone', 'POST', {
						code: code
					}) //获取手机号
					.then(function(v) {
					
						let phone = v.data;
						let useInfo = uni.getStorageSync('useInfo')
						wx.setStorageSync('mobile', mobile)
						resolve(phone);
						myRequest('login', 'POST', {
								openid: uni.getStorageSync('openid'),
								nickname: useInfo.nickName,
								img: useInfo.avatarUrl,
								phone: phone
							}) //传入后台数据
							.then(function(v) {
								uni.navigateBack({
									delta: 1
								})
							}, function(error) {
								reject(error);
							})
					}, function(error) {
						reject(error);
					})
			},
			fail(err) {
				login()
			}
		})
	})
	return promise;
}

module.exports = {
	wechatAppLogin,
	getPhoneNumber
}

